package com.louzhu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.louzhu.common.to.es.SkuEsModel;
import com.louzhu.gulimall.search.config.GulmallElasticsearchConfig;
import com.louzhu.gulimall.search.constant.EsConstant;
import com.louzhu.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 保存商品
     * @param skuEsModelList
     * @return 是否成功
     * @throws IOException
     */
    @Override
    public boolean saveProduct(List<SkuEsModel> skuEsModelList) throws IOException {
        /*
        kibana 中 建立索引 product、映射关系
         */

        /*
        批量保存
         */
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModelList) {
            // 逐一构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            indexRequest.source(JSON.toJSONString(skuEsModel), XContentType.JSON);
            // 逐一添加到批量请求中
            bulkRequest.add(indexRequest);
        }
        // 保存
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, GulmallElasticsearchConfig.COMMON_OPTIONS);
        // 保存失败的数据
        boolean hasFailures = bulkResponse.hasFailures();
        if(hasFailures){
            // 如果出错，记录日志
            BulkItemResponse[] items = bulkResponse.getItems();
            List<String> collect = Arrays.stream(items).filter(item -> {
                return item.isFailed();
            }).map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            log.error("商品数据批量保存到ES出错：{}" , collect);
        }
        // 如果有错误表示失败，没错表示成功
        return !hasFailures;

    }
}
